<script setup>
import { ref, watch, onMounted, computed } from 'vue'
import { useRandomFoodStore } from '@/stores'
import { getRandomFoodAPI } from '@/api/random'

const randomFoodStore = useRandomFoodStore()

const activeIndex = ref(0)
const tabs = ['早饭', '午饭', '晚饭', '米饭', '饮品']
const randomContent = [
  { tabs: '早饭', mealTypes: 'breakfast', buttonText: '早饭吃什么？' },
  { tabs: '午饭', mealTypes: 'lunch', buttonText: '午饭吃什么？' },
  { tabs: '晚饭', mealTypes: 'dinner', buttonText: '晚饭吃什么？' },
  { tabs: '米饭', mealTypes: 'rice', buttonText: '米饭配什么菜？' },
  { tabs: '饮品', mealTypes: 'drink',buttonText: '喝点什么？' }
]

// 监听 tab 切换，重置随机状态
watch(activeIndex, () => {
  isRandom.value = false
})

let isRandom = ref(false)

// 存储随机结果的数据
const randomFoodId = ref('')
const randomFoodImg = ref('')
const randomFoodName = ref('')
const randomFoodLocation = ref('')
const randomFoodShop = ref('')
const isLoading = ref(false)

// 随机获取食物
const getRandomFood = async () => {
  try {
    isLoading.value = true
    const res = await getRandomFoodAPI(activeIndex.value+1)
    
    if (res && res.data) {
      randomFoodId.value = res.data.id
      randomFoodImg.value = res.data.image
      randomFoodName.value = res.data.dishName
      randomFoodLocation.value = res.data.location
      randomFoodShop.value = res.data.merchant
      isRandom.value = true
    } else {
      uni.showToast({
        title: '暂无数据',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取随机食物失败:', error)
    uni.showToast({
      title: '获取失败，请重试',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 已选食物列表
const foodList = ref([])

const getFoodList = () => {
  foodList.value = randomFoodStore.foodList
}

// 添加已选食物
const addSelectedFood = () => {
  randomFoodStore.addFoodToList({
    id: randomFoodId.value,
    img: randomFoodImg.value,
    name: randomFoodName.value,
    location: randomFoodLocation.value,
    shop: randomFoodShop.value,
    addedTime: new Date().toISOString()
  })
  foodList.value = randomFoodStore.foodList
  uni.showToast({
    title: '已添加到列表',
    icon: 'success'
  })
}

// 删除已选食物
const removeSelectedFood = (foodId) => {
  randomFoodStore.removeFoodFromList(foodId)
  foodList.value = randomFoodStore.foodList
  uni.showToast({
    title: '已删除',
    icon: 'success'
  })
}

const clearSelectedFood = () => {
  uni.showModal({
    title: '确认清空',
    content: '确定要清空所有已选食物吗？',
    success: (res) => {
      if (res.confirm) {
        randomFoodStore.clearFoodList()
        foodList.value = randomFoodStore.foodList
        uni.showToast({
          title: '已清空',
          icon: 'success'
        })
      }
    }
  })
}

// 页面加载时获取已选食物列表
onMounted(() => {
  getFoodList()
})

// 统计数据计算
const totalSelectedCount = computed(() => foodList.value.length)
const todaySelectedCount = computed(() => {
  const today = new Date().toDateString()
  return foodList.value.filter(
    (food) => new Date(food.addedTime || new Date()).toDateString() === today
  ).length
})
const favoriteLocation = computed(() => {
  if (foodList.value.length === 0) return '无'
  const locationCount = {}
  foodList.value.forEach((food) => {
    locationCount[food.location] = (locationCount[food.location] || 0) + 1
  })
  const maxLocation = Object.keys(locationCount).reduce((a, b) =>
    locationCount[a] > locationCount[b] ? a : b
  )
  return maxLocation
})
</script>

<template>
  <view class="random-container">
    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stats-card">
        <view class="stats-header">
          <view class="stats-icon">
            <text class="iconfont icon-tongji"></text>
          </view>
          <view class="stats-title">
            <text class="title">今日饮食统计</text>
            <text class="subtitle">让数据见证你的饮食之路</text>
          </view>
        </view>
        <view class="stats-grid">
          <view class="stat-item">
            <view class="stat-number">{{ totalSelectedCount }}</view>
            <view class="stat-label">总计选择</view>
          </view>
          <view class="stat-item">
            <view class="stat-number">{{ todaySelectedCount }}</view>
            <view class="stat-label">今日新增</view>
          </view>
          <view class="stat-item">
            <view class="stat-number">
              {{ favoriteLocation }}
            </view>
            <view class="stat-label">偏爱食堂</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 自定义Tab切换 -->
    <view class="custom-tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="['tab-item', { active: activeIndex === index }]"
        @click="activeIndex = index"
      >
        {{ tab }}
      </view>
    </view>
    
    <view class="tab-content">
      <view class="random-content">
        <view class="tab-pane">
          <view class="default-container" v-if="!isRandom">
            <view class="default-img">
              <image src="/static/images/default.png" alt="" />
            </view>
            <view class="default-text">随机选择饮食</view>
            <button
              type="primary"
              class="default-btn"
              :loading="isLoading"
              @click="getRandomFood"
            >{{ randomContent[activeIndex].buttonText }}</button>
          </view>
          <view class="random-result" v-else>
            <view class="random-img">
              <image :src="randomFoodImg" alt="" />
            </view>
            <view class="random-text">
              <view class="random-name">{{ randomFoodName }}</view>
              <view class="random-location">{{ randomFoodLocation }}</view>
              <view class="random-shop">{{ randomFoodShop }}</view>
            </view>
            <view class="button-group">
              <button
                type="primary"
                class="confirm-btn"
                @click="addSelectedFood"
              >就是你了</button>
              <button
                type="default"
                class="random-btn"
                :loading="isLoading"
                @click="getRandomFood"
              >再来一次</button>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 已选食物列表 -->
    <!-- 已选食物列表区域修改 -->
    <view class="foodlist-container" v-if="foodList.length > 0">
      <view class="foodlist-header">
        <view class="header-left">
          <text class="foodlist-title">已选食物列表</text>
          <text class="foodlist-count">({{ foodList.length }})</text>
        </view>
        <button
          type="warn"
          size="mini"
          class="clear-btn"
          @click="clearSelectedFood"
        >一键清空</button>
      </view>
      
      <!-- 横向滚动容器：与上方内容宽度一致 -->
      <scroll-view 
        scroll-x="true" 
        class="foodlist-scroll"
        show-scrollbar="false"
      >
        <!-- 内容容器：确保内部元素横向排列 -->
        <view class="foodlist-content">
          <view 
            v-for="food in foodList" 
            :key="food.id" 
            class="food-item"
          >
            <view class="food-item-content">
              <image :src="food.img" alt="" class="food-img" />
              <view class="food-info">
                <view class="food-name">{{ food.name }}</view>
                <view class="food-location">{{ food.location }}</view>
                <view class="food-shop">{{ food.shop }}</view>
              </view>
              <view class="remove-btn" @click="removeSelectedFood(food.id)">
                <text class="iconfont icon-shanchu1"></text>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.random-container {
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20rpx 32rpx calc(80rpx + env(safe-area-inset-bottom)) 32rpx;
  overflow-y: auto;
  box-sizing: border-box; /* 确保padding不影响整体宽度 */

  // 统计卡片
  .stats-section {
    margin-bottom: 32rpx;

    .stats-card {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(20px);
      border-radius: 36rpx;
      padding: 40rpx;
      box-shadow: 0 16rpx 56rpx rgba(0, 0, 0, 0.1);
      border: 2rpx solid rgba(255, 255, 255, 0.2);
      position: relative;
      overflow: hidden;
      width: 100%;
      box-sizing: border-box; /* 与父容器宽度对齐 */

      .stats-header {
        display: flex;
        align-items: center;
        margin-bottom: 32rpx;

        .stats-icon {
          width: 84rpx;
          height: 84rpx;
          background: linear-gradient(45deg, #667eea, #764ba2);
          border-radius: 28rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 28rpx;
          box-shadow: 0 8rpx 28rpx rgba(102, 126, 234, 0.3);

          .iconfont {
            color: white;
            font-size: 40rpx;
          }
        }

        .stats-title {
          .title {
            display: block;
            margin: 0 0 6rpx 0;
            font-size: 34rpx;
            font-weight: 600;
            color: #333;
          }

          .subtitle {
            display: block;
            margin: 0;
            font-size: 24rpx;
            color: #999;
          }
        }
      }

      .stats-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 28rpx;

        .stat-item {
          background: rgba(102, 126, 234, 0.05);
          border-radius: 28rpx;
          padding: 28rpx 20rpx;
          text-align: center;
          position: relative;
          transition: all 0.3s ease;
          border: 4rpx solid rgba(102, 126, 234, 0.1);

          .stat-number {
            font-size: 40rpx;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 6rpx;
            line-height: 1;
          }

          .stat-label {
            font-size: 24rpx;
            color: #666;
            font-weight: 500;
            margin-bottom: 16rpx;
          }

          &:nth-child(1) {
            .stat-number { color: #667eea; }
            .stat-icon { background: rgba(102, 126, 234, 0.1); }
          }

          &:nth-child(2) {
            .stat-number { color: #e6a23c; }
            .stat-icon { 
              background: rgba(230, 162, 60, 0.1);
              .iconfont { color: #e6a23c; }
            }
          }

          &:nth-child(3) {
            .stat-number { color: #67c23a; }
            .stat-icon { 
              background: rgba(103, 194, 58, 0.1);
              .iconfont { color: #67c23a; }
            }
          }
        }
      }
    }
  }

  // 自定义Tab切换样式
  .custom-tabs {
    margin-bottom: 40rpx;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 36rpx;
    box-shadow: 0 16rpx 56rpx rgba(0, 0, 0, 0.1);
    border: 2rpx solid rgba(255, 255, 255, 0.2);
    overflow: hidden;
    display: flex;
    width: 100%;
    box-sizing: border-box; /* 与父容器宽度对齐 */
    
    .tab-item {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      font-size: 28rpx;
      color: #666;
      background: transparent;
      transition: all 0.3s ease;
      position: relative;
      
      &.active {
        background: #667eea;
        color: white;
        font-weight: 600;
      }
      
      &:not(:last-child)::after {
        content: '';
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 1rpx;
        height: 60%;
        background: rgba(102, 126, 234, 0.1);
      }
      
      &.active + .tab-item::after,
      &.active::after {
        display: none;
      }
    }
  }

  // Tab内容区域
  .tab-content {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 36rpx;
    box-shadow: 0 16rpx 56rpx rgba(0, 0, 0, 0.1);
    border: 2rpx solid rgba(255, 255, 255, 0.2);
    overflow: hidden;
    margin-bottom: 40rpx;
    padding: 32rpx;
    width: 100%;
    box-sizing: border-box; /* 与父容器宽度对齐 */

    .random-content {
      min-height: 560rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .tab-pane {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 560rpx;
      }

      // 默认状态
      .default-container {
        text-align: center;
        max-width: 600rpx;

        .default-img {
          margin-bottom: 40rpx;

          image {
            width: 300rpx;
            height: 300rpx;
            border-radius: 36rpx;
            box-shadow: 0 16rpx 40rpx rgba(0, 0, 0, 0.1);
          }
        }

        .default-text {
          font-size: 36rpx;
          color: #666;
          margin-bottom: 60rpx;
          font-weight: 500;
        }

        .default-btn {
          width: 400rpx;
          height: 88rpx;
          line-height: 88rpx;
          background: linear-gradient(45deg, #667eea, #764ba2);
          border: none;
          border-radius: 44rpx;
          color: white;
          font-size: 32rpx;
          font-weight: 600;
          box-shadow: 0 12rpx 32rpx rgba(102, 126, 234, 0.4);
        }
      }

      // 随机结果状态
      .random-result {
        text-align: center;
        max-width: 600rpx;
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(20px);
        border-radius: 36rpx;
        padding: 40rpx;
        box-shadow: 0 16rpx 56rpx rgba(0, 0, 0, 0.1);
        border: 2rpx solid rgba(255, 255, 255, 0.2);
        animation: fadeInUp 0.5s ease;

        .random-img {
          margin-bottom: 30rpx;

          image {
            width: 200rpx;
            height: 200rpx;
            border-radius: 24rpx;
            box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
          }
        }

        .random-text {
          margin-bottom: 40rpx;

          .random-name {
            font-size: 36rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 20rpx;
          }

          .random-location {
            font-size: 26rpx;
            color: #667eea;
            background: rgba(102, 126, 234, 0.1);
            padding: 8rpx 16rpx;
            border-radius: 16rpx;
            display: inline-block;
            margin-right: 16rpx;
            margin-bottom: 16rpx;
          }

          .random-shop {
            font-size: 26rpx;
            color: #e6a23c;
            background: rgba(230, 162, 60, 0.1);
            padding: 8rpx 16rpx;
            border-radius: 16rpx;
            display: inline-block;
          }
        }

        .button-group {
          display: flex;
          justify-content: center;
          align-items: center;
          gap: 24rpx;
        }

        .confirm-btn,
        .random-btn {
          width: 180rpx;
          height: 60rpx;
          line-height: 60rpx;
          border-radius: 30rpx;
          font-size: 24rpx;
          font-weight: 600;
          border: none;
          margin: 0;
        }

        .confirm-btn {
          background: linear-gradient(45deg, #67c23a, #85ce61);
          color: white;
          box-shadow: 0 8rpx 24rpx rgba(103, 194, 58, 0.3);
        }

        .random-btn {
          background: rgba(102, 126, 234, 0.1);
          color: #667eea;
          border: 2rpx solid rgba(102, 126, 234, 0.2);
        }
      }
    }
  }

  // 已选食物列表（核心优化区域）
  .foodlist-container {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 36rpx;
    padding: 36rpx;
    box-shadow: 0 16rpx 56rpx rgba(0, 0, 0, 0.1);
    border: 2rpx solid rgba(255, 255, 255, 0.2);
    margin-top: 40rpx;
    width: 100%;
    box-sizing: border-box; /* 与上方内容宽度严格一致 */

    .foodlist-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 28rpx;

      .header-left {
        display: flex;
        align-items: baseline;
        gap: 8rpx;
      }

      .foodlist-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }

      .foodlist-count {
        font-size: 24rpx;
        color: #999;
        font-weight: normal;
      }

      .clear-btn {
        background: linear-gradient(45deg, #f56c6c, #f78989);
        color: white;
        border: none;
        border-radius: 20rpx;
        padding: 12rpx 24rpx;
        font-size: 24rpx;
        font-weight: 600;
        box-shadow: 0 6rpx 16rpx rgba(245, 108, 108, 0.3);
      }
    }

    // 横向滚动容器（核心优化）
    .foodlist-scroll {
      width: 100%; /* 与容器宽度一致 */
      overflow-x: auto; /* 横向滚动 */
      overflow-y: hidden;
      padding: 10rpx 0;
      box-sizing: border-box;
      -webkit-overflow-scrolling: touch; /* 平滑滚动 */
    }

    // 列表内容容器（确保内部元素横向排列）
    .foodlist-content {
      display: inline-flex; /* 横向排列 */
      gap: 28rpx; /* 项间距，替代margin-right */
      padding-bottom: 10rpx; /* 避免滚动条遮挡内容 */
    }

    // 单个食物项样式
    .food-item {
      flex-shrink: 0; /* 禁止收缩，保证宽度一致 */
      width: 220rpx;
      min-height: 280rpx;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 24rpx;
      padding: 24rpx;
      text-align: center;
      border: 4rpx solid rgba(102, 126, 234, 0.1);
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;

      .food-item-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
      }

      .food-img {
        width: 112rpx;
        height: 112rpx;
        border-radius: 16rpx;
        margin-bottom: 16rpx;
        box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
        object-fit: cover; /* 图片裁剪适配 */
      }

      .food-info {
        width: 100%;

        .food-name {
          font-size: 26rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 8rpx;
          line-height: 1.2;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .food-location {
          font-size: 20rpx;
          color: #667eea;
          background: rgba(102, 126, 234, 0.1);
          padding: 4rpx 8rpx;
          border-radius: 8rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          margin-bottom: 6rpx;
        }

        .food-shop {
          font-size: 20rpx;
          color: #e6a23c;
          background: rgba(230, 162, 60, 0.1);
          padding: 4rpx 8rpx;
          border-radius: 8rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .remove-btn {
        position: absolute;
        top: 12rpx;
        right: 12rpx;
        width: 44rpx;
        height: 44rpx;
        background: rgba(245, 108, 108, 0.9);
        border-radius: 50%;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        backdrop-filter: blur(10px);
        box-shadow: 0 6rpx 16rpx rgba(245, 108, 108, 0.4);
        z-index: 10;
        transition: transform 0.2s ease;

        .iconfont {
          font-size: 20rpx;
        }

        &:active {
          transform: scale(0.9); /* 点击反馈 */
        }
      }
    }

    // 隐藏滚动条（可选，美化效果）
    .foodlist-scroll::-webkit-scrollbar {
      display: none;
    }
  }
}

// 动画定义
@keyframes gradientShift {
  0%, 100% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
